import { useEffect } from "react";
import { theme } from "antd";
import { useGlobalStore } from "@/store/global";
import { useShallow } from "zustand/react/shallow";
import { setStyleProperty } from "@/utils";
import { getLightColor, getDarkColor } from "@/utils/color";

/**
 * @description  设置全局主题钩子
 */
const useTheme = () => {
  const { token } = theme.useToken();

  const { isDark, colorPrimary, isGrey, isWeak, siderInverted, headerInverted } = useGlobalStore(
    useShallow((state) => ({ isDark: state.isDark, colorPrimary: state.colorPrimary, isGrey: state.isGrey, isWeak: state.isWeak, siderInverted: state.siderInverted, headerInverted: state.headerInverted }))
  );

  /**
   * @description 切换深色模式
   */
  useEffect(() => switchDark(), [isDark]);
  const switchDark = () => {
    isDark && document.documentElement.classList.add("dark");
    !isDark && document.documentElement.classList.remove("dark");
    changePrimary();
  };

  /**
   * @description 切换侧边栏背景颜色
   */
  useEffect(() => switchSiderInverted(), [siderInverted]);
  const switchSiderInverted = () => {
    siderInverted && document.documentElement.classList.add("siderInverted");
    !siderInverted && document.documentElement.classList.remove("siderInverted");
  };

  /**
   * @description 切换头部背景颜色
   */
  useEffect(() => switchHeaderInverted(), [headerInverted]);
  const switchHeaderInverted = () => {
    headerInverted && document.documentElement.classList.add("headerInverted");
    !headerInverted && document.documentElement.classList.remove("headerInverted");
  };

  /**
   * @description 切换主题色
   */
  useEffect(() => changePrimary(), [colorPrimary]);
  const changePrimary = () => {
    const tokens = [
      "colorBgContainer",
      "colorBorderSecondary",
      "fontSizeLG",
      "colorPrimaryText",
      "colorIcon",
      "colorIconHover",
      "borderRadius",
      "colorFill",
      "colorText",
      "colorPrimary",
      "borderRadiusSM",
      "colorPrimary5",
      "colorPrimary8",
      "colorTextTertiary",
      "paddingLG",
      "borderRadiusLG",
      // 登录页
      "boxShadowAnalysis"
    ];
    // antd css variable
    Object.entries(token).forEach(([key, val]) => tokens.includes(key) && setStyleProperty(`--el-color-${key}`, val));
    // antd primaryColor css variable
    for (let i = 1; i <= 9; i++) {
      setStyleProperty(`--el-color-colorPrimary${i}`, isDark ? `${getDarkColor(colorPrimary, i / 10)}` : `${getLightColor(colorPrimary, i / 10)}`);
    }
  };

  /**
   * @description 灰色和色弱之间切换
   */
  useEffect(() => changeGreyOrWeak(), [isGrey, isWeak]);
  const changeGreyOrWeak = () => {
    document.documentElement.style.filter = isWeak ? "invert(80%)" : isGrey ? "grayscale(1)" : "";
  };
};

export default useTheme;
